<template>
  <div>
    <el-form
      ref="formItem"
      :model="formItem"
      :rules="formItemRule"
      label-width="100px"
      @submit.native.prevent
      v-loading="loading"
    >
      <div class="form-layout">
        <el-form-item label="门店id：" v-if="formItem.id">
          <el-input disabled v-model="formItem.id" placeholder></el-input>
        </el-form-item>
        <el-form-item label="门店名称：" prop="title">
          <el-input v-model="formItem.title" placeholder="请输入门店名称"></el-input>
        </el-form-item>
        <el-form-item label="联系人：" prop="linkName">
          <el-input v-model="formItem.linkName" placeholder="请输入联系人"></el-input>
        </el-form-item>
        <el-form-item label="联系人手机：" prop="linkMobile">
          <el-input v-model="formItem.linkMobile" placeholder="请输入联系人手机"></el-input>
        </el-form-item>
        <el-form-item label="提醒人手机：" prop="linkMobile">
          <el-input v-model="formItem.remindMobile" placeholder="请输入提醒人手机"></el-input>
        </el-form-item>
        <el-row style="grid-column: 1/-1;" >
          <el-col :span="12">
            <el-form-item label="所属城市：" prop="cityId">
              <el-select v-model="formItem.cityId" :clearable="true" :filterable="true">
                <el-option
                  v-for="(item, index) in cityList"
                  :key="index"
                  :value="item.id"
                  :label="item.cityName"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row style="grid-column: 1/-1;">
          <el-col :span="12">
            <el-form-item label="登录帐号：" prop="loginName" style="grid-column: 1/-1;">
              <el-input v-model="formItem.loginName" placeholder="请输入登录帐号" style="width: 100%;"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="登录密码：" prop="pwd" style="grid-column: 1/-1;">
              <el-input v-model="formItem.pwd" placeholder="请输入登录密码，为空则不修改" style="width: 100%;"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="简介：" style="grid-column: 1 / -1;">
          <el-input
            type="textarea"
            :autosize="{minRows: 5, maxRows: 6}"
            v-model.trim="formItem.shortDesc"
            placeholder="请输入简介"
          ></el-input>
        </el-form-item>

        <el-form-item label="门店类型：" style="grid-column: 1 / -1;">
          <el-radio-group v-model="formItem.companyType">
            <el-radio :label="1">
              <span>可接单不发布服务型</span>
            </el-radio>
            <el-radio :label="2">
              <span>可接单可发布服务型</span>
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-row style="grid-column: 1 / -1;">
          <el-col :span="12">
            <el-form-item label="封面图片：" prop="image">
              <div class="upLoadPicBox" @click="modalPicTapDan(false,'thumb')">
                <div v-if="formItem.thumb" class="pictrue">
                  <img :src="formItem.thumb" />
                </div>
                <div v-else class="upLoad">
                  <i class="el-icon-camera cameraIconfont" />
                </div>
                <div class="from-tips">建议尺寸(180*180)</div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="营业执照：" prop="sliderImages" style="grid-column: 1 / -1;">
          <div class="acea-row">
            <div
              v-for="(item, index) in formItem.certArray"
              :key="index"
              class="pictrue"
              draggable="true"
            >
              <img :src="item" />
              <i
                v-if="!isDisabled"
                class="el-icon-error btndel"
                @click="handleRemove(index,'certArray')"
              />
            </div>
            <div
              v-if="formItem.certArray.length < 8"
              class="upLoadPicBox"
              @click="modalPicTap(true,'certArray')"
            >
              <div class="upLoad">
                <i class="el-icon-camera cameraIconfont" />
              </div>
            </div>
          </div>
          <div style="color: #999;">（最多上传8张）</div>
        </el-form-item>

        <el-form-item label="详细地址:" style="grid-column: 1 / -1;">
          <el-input
            type="textarea"
            :autosize="{minRows: 3, maxRows: 3}"
            v-model.trim="formItem.detail"
            placeholder="请输入详细地址"
          ></el-input>
        </el-form-item>
        <el-form-item label="经纬度：" prop="latlng" style="grid-column: 1 / -1;">
          <el-tooltip content="请点击查找位置选择位置">
            <el-input v-model="formItem.latlng" style="width: 100%" placeholder="请查找位置">
              <el-button @click="onSearch" type="primary" slot="append" icon="el-icon-search"></el-button>
            </el-input>
          </el-tooltip>
        </el-form-item>
        <el-row>
          <el-col :span="24" >
            <el-form-item label="酬劳比例(%)：">
              <el-input-number :max="100" :min="0" :step="1" v-model="formItem.companyRate" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="排序：">
              <el-input-number
                placeholder="请输入排序"
                element-id="sort"
                :precision="0"
                v-model="formItem.sort"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
    <!-- 地图弹框 -->
    <el-dialog
      :visible.sync="modalMap"
      footer-hide
      title="请选择地址"
      :append-to-body="true"
    >
      <iframe id="mapPage" width="100%" height="1000px" frameborder="0" v-bind:src="keyUrl"></iframe>
    </el-dialog>
  </div>
</template>

<script>
import { cityList, getCompanyFromDataApi,saveCompanyApi } from '@/api/base';
// import { cityList } from '@/api/app';
// import { keyApi } from '@/api/setting';
export default {
  name: 'companyEdit',
  props: {
    // modals: {
    //   default: false,
    //   type: Boolean,
    // },
    id: {
      default: 0,
    },
  },
  watch: {},
  data() {
    var checkCityId = (rule, val ,callback)=>{
      if(!val){
        return callback(new Error('请选择城市'))
      }
      callback()
    }
    return {
      loading: false,
      images: '',
      isChoice: '单选',
      modals: false,
      modalPic: false,
      labelShow: false,
      modalMap: false,
      orderStatus: 0,
      total_num: 0,
      splitSwitch: true,
      keyUrl: '',
      addresData: [],
      grid: {
        xl: 8,
        lg: 8,
        md: 12,
        sm: 24,
        xs: 24,
      },
      gridPic: {
        xl: 6,
        lg: 8,
        md: 12,
        sm: 12,
        xs: 12,
      },
      gridBtn: {
        xl: 4,
        lg: 8,
        md: 8,
        sm: 8,
        xs: 8,
      },
      formItem: {
        title: '',
        shortDesc: '',
        thumb: '',
        loginName:'',
        linkName: '',
        linkMobile: '',
        cityId: '',
        latitude: '',
        longitude: '',
        latlng: '',
        status: 0,
        loginName: '',
        pwd: '',
        sort: 0,
        detail: '',
        certArray: [],
        companyType: 1,
        companyRate: 0,
        address: [],
        remindMobile:''
      },
      formItemRule:{
        title:[{required:true, message:'请输入名称',trigger:'blur'}],
        loginName:[{required:true, message:'请输入联系人',trigger:'blur'}],
        linkMobile:[{required:true, message:'请输入联系人手机',trigger:'blur'}],
        cityId:[{required:true, validator:checkCityId,trigger:'change'}]
      },
      dataLabel: [],
      cityList: [],
    };
  },
  created() {
    this.getCityList();
  },
  mounted() {
    // this.loading = true;
    // 把父组件在带过来的数据绑定到组件数据中
    if (this.id) {
      this.getCompanyDetail();
    }
    window.addEventListener(
      'message',
      function (event) {
        // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
        var loc = event.data;
        if (loc && loc.module === 'locationPicker') {
          // 防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
          window.parent.selectAdderss(loc);
        }
      },
      false,
    );
    window.selectAdderss = this.selectAdderss;
    this.loading = false;
  },
  methods: {
    getCompanyDetail() {
      getCompanyFromDataApi({ id: this.id }).then((res) => {
        let data = res;
        console.log(data)
        this.formItem.title = data.title;
        this.formItem.shortDesc = data.shortDesc;
        this.formItem.thumb = data.thumb;
        this.formItem.cityId = data.cityId;
        this.formItem.linkName = data.linkName;
        this.formItem.linkMobile = data.linkMobile;
        this.formItem.loginName = data.loginName;
        this.formItem.ctiyId = data.ctiyId;
        this.formItem.latitude = data.latitude;
        this.formItem.longitude = data.longitude;
        this.formItem.status = data.status;
        this.formItem.detail = data.detail;
        this.formItem.certArray = data.certArray||[];
        this.formItem.companyType = data.companyType;
        this.formItem.companyRate = data.companyRate;
        this.formItem.remindMobile = data.remindMobile;
        
        if (this.formItem.latitude) {
          this.formItem.latlng = this.formItem.latitude + ',' + this.formItem.longitude;
        }
        if (this.formItem.province) {
          this.formItem.address = [this.formItem.province, this.formItem.city, this.formItem.district];
        }
      });
    },
    getCityList() {
      cityList({page:1,limit: 999}).then((res) => {
        let data = res;
        this.cityList = data.list;
      });
    },
    submit(){
        this.$refs.formItem.validate(valid => {
            if(valid){
                let form = this.formItem;
                form.id = this.id;
                if(!form.pwd){
                  delete form.pwd;
                }
                saveCompanyApi(form).then(res => {
                    this.$message.success('操作成功');
                    this.$emit('submitSuccess')
                }).catch(err => {
                    this.$message.error('操作失败');
                })
            }
        })
    },
    // 选择经纬度
    selectAdderss(data) {
      console.log('place', data);
      this.formItem.detail = data.poiname;
      (this.formItem.latitude = data.latlng.lat),
        (this.formItem.longitude = data.latlng.lng),
        (this.formItem.latlng = data.latlng.lat + ',' + data.latlng.lng);
      this.modalMap = false;
    },
    // 选择位置
    onSearch() {
        this.keyUrl = `https://apis.map.qq.com/tools/locpicker?type=1&key=UAXBZ-BVZCW-H26RV-YEIPR-IS4VE-Z3FIA&referer=myapp`;
        this.modalMap = true;


    //   if (!this.keyUrl) {
    //     keyApi()
    //       .then(async (res) => {
    //         let keys = res.data.key;
    //         this.keyUrl = `https://apis.map.qq.com/tools/locpicker?type=1&key=${keys}&referer=myapp`;
    //         this.modalMap = true;
    //       })
    //       .catch((res) => {
    //         this.$Message.error(res.msg);
    //       });
    //   } else {
    //     this.modalMap = true;
    //   }
    },
    modalPicTapDan(multiple,index) {
      const _this = this;
      const attr = [];
      this.$modalUpload(
        function (img) {
          if (!img) return;
          _this.formItem.thumb = img[0].sattDir;
        },
        multiple,
        'store',
      );
    },
    modalPicTap(multiple, index) {
      const _this = this;
      this.$modalUpload(
        function (img) {
          if (!img) return;
          if (img.length > 10) return this.$message.warning('最多选择8张图片！');
          if (img.length + _this.formItem[index].length > 10) return this.$message.warning('最多选择8张图片！');
          img.map((item) => {
            _this.formItem[index].push(item.sattDir);
          });
        },
        multiple,
        'store',
      );
    },
    handleRemove(i, index) {
      this.formItem[index].splice(i, 1);
    },
    // 移动
    handleDragStart(e, item) {
      this.dragging = item;
    },
    handleDragEnd(e, item) {
      this.dragging = null;
    },
    handleDragOver(e) {
      e.dataTransfer.dropEffect = 'move';
    },
    handleDragEnter(e, item, index) {
      e.dataTransfer.effectAllowed = 'move';
      if (item === this.dragging) {
        return;
      }
      const newItems = [...this.formItem[index]];
      const src = newItems.indexOf(this.dragging);
      const dst = newItems.indexOf(item);
      newItems.splice(dst, 0, ...newItems.splice(src, 1));
      this.formItem[index] = newItems;
    },
  },
};
</script>

<style lang="stylus" scoped>
.labelInput {
  border: 1px solid #dcdee2;
  width: 400px;
  padding: 0 8px;
  border-radius: 5px;
  min-height: 30px;
  cursor: pointer;

  .span {
    color: #c5c8ce;
  }

  .iconxiayi {
    font-size: 12px;
  }
}

.ivu-form-item {
  margin-bottom: 10px;
}

.form-sty {
  width: 400px !important;
}

.addfont {
  display: inline-block;
  font-size: 13px;
  font-weight: 400;
  color: #1890FF;
  margin-left: 14px;
  cursor: pointer;
  margin-left: 10px;
}

.ivu-icon-ios-arrow-down {
  font-size: 14px;
}

.tip {
  color: #bbb;
}

.picBox {
  display: inline-block;
  cursor: pointer;

  .upLoad {
    width: 58px;
    height: 58px;
    line-height: 58px;
    border: 1px dotted rgba(0, 0, 0, 0.1);
    border-radius: 4px;
    background: rgba(0, 0, 0, 0.02);
  }

  .pictrue {
    width: 60px;
    height: 60px;
    border: 1px dotted rgba(0, 0, 0, 0.1);
    margin-right: 10px;

    img {
      width: 100%;
      height: 100%;
    }
  }

  .iconfont {
    color: #898989;
  }
}

.pictrue {
  width: 60px;
  height: 60px;
  border: 1px dotted rgba(0, 0, 0, 0.1);
  margin-right: 10px;

  img {
    width: 100%;
    height: 100%;
  }
}

.tabBox-add {
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid;
  border-color: #ddd;
}

.pic-lis {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;

  .pic-box {
    flex-shrink: 0;
    width: 38px;
    height: 38px;
    margin-right: 10px;
    position: relative;

    img {
      width: 100%;
      height: 100%;
      object-fit: contain cursor pointer;
      transition: all 0.5s;
    }

    button {
      position: absolute;
      right: -10px;
      top: -10px;
      width: 20px;
      height: 20px;
      opacity: 0;
      transition: all 0.5s;
    }

    &:hover {
      border-radius: 6px;

      img {
        transform: scale(1.4);
        transition: all 0.5s;
      }

      button {
        opacity: 0.8;
      }
    }
  }
}

.form-layout {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 10px;
}

.textarea-1 {
  width: 100%;
  padding: 0 10px;
  border: none;
  background: #f5f5f5;
  border-radius: 6px;
  min-height: 50px;
}

.textarea-1:focus {
  outline: 1px solid #dcdee2;
}

.textarea-1:hover {
  outline: 1px solid #dcdee2;
}
</style>